package com.rzico.quartz.job;

import com.rzico.account.entity.PhoneRefunds;
import com.rzico.account.entity.Refunds;
import com.rzico.account.service.PhoneRefundsService;
import com.rzico.core.entity.SysJob;
import com.rzico.core.service.SysJobService;
import com.rzico.market.entity.PhoneOrder;
import com.rzico.market.enumx.PhoneOrderStatusEnum;
import com.rzico.market.service.PhoneOrderService;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 豆讯话费订单30分钟未未支付订单关闭
 * Created by zhongzm on 2020/2/2.
 * 计划任务执行demo
 */
public class DXPhoneOrderQueryTask implements Job {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    protected SysJobService sysJobService;

    @Autowired
    protected PhoneOrderService phoneOrderService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String jobId = jobExecutionContext.getTrigger().getKey().getName();
        SysJob sysJob = sysJobService.selectByPrimaryKey(jobId);
        try {
            if (sysJob.getExecStatus().equals(1)) {
                //不能重复执行
                return;
            }
            sysJob.setExecStatus(1);
            sysJob.setJobDesc("开始执行:"+sdf.format(new Date()));
            sysJobService.updateByPrimaryKeySelective(sysJob);

            // 每10分钟检测一次,已支付的话费充值订单，若失败生成退款单
            Map<String, Object> orderParams = new HashMap<String, Object>();
            orderParams.put("orderMethod",0);
            orderParams.put("orderStatus", PhoneOrderStatusEnum.ORDER_STATUS_UNCONFIRM.getId());
            orderParams.put("paymentStatus", PhoneOrderStatusEnum.PAYMENT_STATUS_WAITING.getId());
            orderParams.put("beforeDate", DateUtils.addMinutes(new Date(),-30));
            List<PhoneOrder> phoneOrderList = phoneOrderService.selectList(orderParams);
            for (PhoneOrder po : phoneOrderList) {
                phoneOrderService.cancel(po.getId());
            }
            // end

            sysJob.setExecStatus(0);
            sysJob.setJobDesc("执行成功:"+sdf.format(new Date())+",下次执行:"+sdf.format(jobExecutionContext.getNextFireTime()));
            sysJobService.updateByPrimaryKeySelective(sysJob);
        }
        catch (Exception e) {
            sysJob.setExecStatus(0);
            sysJob.setJobDesc("执行错误:"+sdf.format(new Date()));
            sysJobService.updateByPrimaryKeySelective(sysJob);
        }

    }
}
